package com.baaio.conn;

import static com.baaio.util.Out.print;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import com.baaio.util.GetInfo;
/**
 * 此类在jdbc的基础上写的事务处理类。<br>
 * 该类的构造方法为被隐藏。<br>
 * TransactionFactory 提供了两个方法可以得到该类的实例。<br>
 * 分别是 ：<br>
 *  createTransaction()<br>
 *  createTransaction(String DBName)<br>
 * 
 *
 */
public class Transaction
{

	private Connection dbconn = null;
	private Statement dbstate = null;
	private ArrayList<String> query;
	private GetStatement gstm;
	private boolean f = true;
	private TransactionConnImpl baaio;

	protected Transaction(String DBName)
	{

		gstm = new GetStatement(DBName,true);
		dbstate = gstm.getStatement();
		dbconn = gstm.getDbconn();
		baaio = getBaaio(DBName);
	}

	protected Transaction()
	{

		gstm = new GetStatement(GetInfo.getInstance().getDb(),true);
		dbstate = gstm.getStatement();
		dbconn = gstm.getDbconn();
		baaio = getBaaio();
	}
	/**
	 * 获得事务的实现类TransactionConnImpl
	 * 
	 * @return TransactionConnImpl
	 */
	public TransactionConnImpl getBaaio()
	{

		return TransactionConnImpl.getBaaioInstance();
	}
	/**
	 * 获得事务的实现类TransactionConnImpl
	 * 
	 * @return TransactionConnImpl
	 */
	public TransactionConnImpl getBaaio(String DBName)
	{

		return TransactionConnImpl.getBaaioInstance(DBName);
	}
	
	protected void invoke()
	{
		if (f)
		{
			try
			{
				dbconn.commit();
				baaio.clear();
				dbconn.close();
			}
			catch (SQLException e)
			{
				e.printStackTrace();
			}
		}
		
	}

	protected boolean invokeAll()
	{

		query = baaio.getList();
		int k = 1; 
		int ik = 1; 
		try
		{
			dbconn.setAutoCommit(false);
			for (String sql : query)
			{
				print("第 " + ik + " 条  Sql = " + sql);
				dbstate.addBatch(sql);
				ik++;
			}
			int[] updateCounts = dbstate.executeBatch();

			
			for (int i : updateCounts)
			{
				if (i == 0 || i < 0)
				{
					f = false;
					print("第" + k + "条sql语句执行失败，请检查");
					break;
				}
				k++;
			}
			
		}
		catch (Exception e)
		{
			print("第：" + k + "条sql语句执行失败，请检查");
			e.printStackTrace();
		}
		return f;
	}

}
